#include <sstream>
#include <string>
#include <cstring>
#include "TcpClient.hpp"
#include "Protocol.hpp"
#include "Sock.hpp"
#include "log.hpp"

using namespace protocol_ns;
// 单独封起来

enum
{
    LEFT,
    OPER,
    RIGHT
};

// 10+20
Request ParseLine(const std::string &line)
{
    std::string left, right;
    char op;
    int status = LEFT;

    int i = 0;
    while(i < line.size())
    {
        // if(isdigit(e)) left.push_back;

        switch (status)
        {
        case LEFT:
            if (isdigit(line[i]))
                left.push_back(line[i++]);
            else
                status = OPER;
            break;
        case OPER:
            op = line[i++];
            status = RIGHT;
            break;
        case RIGHT:
            if (isdigit(line[i]))
                right.push_back(line[i++]);
            break;
        }
    }

    Request req;

    req._x = std::stoi(left);
    req._y = std::stoi(right);
    req._op = op;

    return req;
}

int main(int argc, char* argv[])
{
    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);

    Sock sock;
    sock.Socket();
    sock.Connect(server_ip, server_port);

    std::string buffer;
    while(true)
    {
        std::cout << "Enter# ";
        std::string message;
        std::getline(std::cin, message);
        // 1. 创建请求
        Request req;
        req = ParseLine(message);
        // std::cout << req._x << req._op << req._y << std::endl;
        // 2. 将请求序列化并发送
        std::string send_string;
        req.Serialize(&send_string);
        send_string = AddHeader(send_string);
        std::cout << send_string << std::endl;
        send(sock.GetFd(), send_string.c_str(), send_string.size(), 0);

        // 3. 取回结果
        std::string package;
        int n = 0;
        do
        {
            n = ReadPackage(sock.GetFd(), buffer, &package);
        } while (!n);
        
        package = RemoveHeader(package, n);
        Response resp;
        resp.Deserialize(package);

        std::cout << "result: " << resp._result << ", code: " << resp._code << std::endl;
    }
    return 0;
}